# This test script performs the fifth of the benchmarks presented in
# the paper I am submitting to mobisys '10. 
#
# This benchmark is intended to show the benefits of using an adaptive 
# profile. A task is performed using the combined profiling scheduler 
# and the adaptive scheduler. The input images are a small and a large 
# image. The small image is used five (5) times and the large one two 
# (2) times.
#
# The input images used in the paper can be found in testdata/percom.

from __future__ import with_statement
import sys
import scavenger
from time import sleep, time

# Check command line args.
if len(sys.argv) < 4 or not '-s' in sys.argv:
    print 'Usage: mobisys5.py imagefile -s scheduler [-i iterations]'
    sys.exit(1)

# Read in the image files.
images = []
for x in range(1,8):
    with open(sys.argv[1] + str(x) + '.jpg', 'rb') as infile:
        images.append(infile.read())

# Find out which scheduler to use.
scheduler = sys.argv[sys.argv.index('-s') + 1]
if not scheduler in ('comb', 'adaptive'):
    print 'Invalid scheduler. Valid values are comb and adaptive.'
    sys.exit(1)

# Check whether a number of test iterations is given.
iterations = 1
if '-i' in sys.argv:
    iterations = int(sys.argv[sys.argv.index('-i') + 1])

# Sleep for a little while to make sure that we discover
# the available surrogates.
sleep(2.0)

@scavenger.cprofilescavenge('len(#0)')
def cbrightness(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.aprofilescavenge('len(#0)', 'len(#0)')
def abrightness(image, factor):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

function = None
if scheduler == 'comb':
    function = cbrightness
else:
    function = abrightness

# Run the test!
for x in range(0, iterations):
    for y in [0,0,0,0,0,6,6]:
        start = time()
        try:
            function(images[y], 1.3)
        except:
            print 'error',
        stop = time()
        print 'image%i: '%y + str(stop - start)
    
scavenger.shutdown()
